<script setup>
import { ref, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { pageQueryEmp, addEmp, getEmpById, updateEmpById, deleteEmpById } from "@/api/emp";
import { queryAllDepts } from "@/api/dept";

//定义数据
const searchForm = ref({
  name: "",
  gender: "",
  begin: "",
  end: "",
  daterange: []
});
const tableData = ref([]);
const page = ref(1);
const pageSize = ref(5);
const total = ref(0);
const empForm = ref({
  "image": "",
  "username": "",
  "name": "",
  "gender": "",
  "job": "",
  "entryDate": "",
  "deptId": "",
  "phone": "",
  "salary": "",
  "exprList": []
});
const dialogFormVisible = ref(false);
const dialogTitle = ref("新增员工");
const genders = ref([
  { value: 1, name: "男" },
  { value: 2, name: "女" }
]);
const jobs = ref([
  { value: 1, name: "班主任" },
  { value: 2, name: "讲师" },
  { value: 3, name: "学工主管" },
  { value: 4, name: "教研主管" },
  { value: 5, name: "咨询师" }
]);
const depts = ref([]);
const selectedIds = ref([]);
const userToken = ref("");

//侦听empForm里的exprList
watch(() => empForm.value.exprList, (newValue, oldValue) => {
  newValue.forEach(expr => {
    const range = expr.exprrange;
    if (range && range.length == 2) {
      expr.begin = range[0];
      expr.end = range[1];
    }
  });
}, { deep: true });

function addExpr() {
  //js里向数组中添加一个元素：push
  empForm.value.exprList.push({ company: "", job: "", begin: "", end: "", exprrange: [] });
}
function removeExpr(index) {
  //js里从数组中删除元素：splice(索引,删除数量)，从指定索引开始，删除指定数量
  empForm.value.exprList.splice(index, 1);
}

async function save() {
  let result;

  //判断dialg里表单数据有没有id，如果有id那么要执行修改
  if (empForm.value.id) {
    result = await updateEmpById(empForm.value);
  } else {
    //没有id则执行新增
    result = await addEmp(empForm.value);
  }

  if (result.code == 1) {
    ElMessage.success("保存成功");
    dialogFormVisible.value = false;
    search();
  } else {
    ElMessage.error("保存失败");
  }
}

//监听searchForm里的daterange：如果值有变化，就取开始日期赋值给begin，结束日期赋值给end
watch(() => searchForm.value.daterange, (newValue, oldValue) => {
  //如果改变之后的新值非空，并且数组的长度为2，再执行：
  if (newValue && newValue.length == 2) {
    searchForm.value.begin = newValue[0];
    searchForm.value.end = newValue[1];
  }
});

async function search() {
  //todo 暂时将页码和每页数量参数写死了，等后续添加了分页功能之后，要获取实际的页码和分页数量
  const result = await pageQueryEmp(searchForm.value, page.value, pageSize.value);
  if (result.code == 1) {
    //取分页查询结果的列表，设置给表格
    tableData.value = result.data.rows;
    //取分页查询结果的总数量：
    total.value = result.data.total;
  } else {
    ElMessage.error("查询员工失败");
  }
}

//页面加载完成
onMounted(async () => {
  // 立即显示员工表格
  search();
  // 向后端发请求加载所有部门，用于 部门下拉框里作为下拉选项
  const result = await queryAllDepts();
  if (result.code == 1) {
    depts.value = result.data;
  }
  // 从localStorage里取当前用户的令牌，设置给userToken变量
  const loginInfoStr = localStorage.getItem("loginInfo");
  if (loginInfoStr) {
    const loginInfo = JSON.parse(loginInfoStr);
    userToken.value = loginInfo.token;
  }
})

//每页数量变化时触发
const handleSizeChange = (val) => {
  //将页码重置为1
  page.value = 1;
  //再向后端发请求
  search();
}
//当前页码变化时触发
const handleCurrentChange = (val) => {
  //重新向后端发请求查询员工列表
  search();
}

function research() {
  // 将搜索条件全部置空
  searchForm.value = {
    name: "",
    gender: "",
    begin: "",
    end: "",
    daterange: []
  };
  // 重新向后端发请求
  search();
}

function showAddWin() {
  //1. dialog内表单数据置为空 todo
  empForm.value = {
    "image": "",
    "username": "",
    "name": "",
    "gender": "",
    "job": "",
    "entryDate": "",
    "deptId": "",
    "phone": "",
    "salary": "",
    "exprList": []
  };
  //2. 将dialog的标题设置为“新增员工”
  dialogTitle.value = "新增员工";
  //3. 将dialog窗口显示出来
  dialogFormVisible.value = true;
}
//当表格选中行变化时触发的，val是 所有被选中的行数据数组[]，一行是一个对象{"id":1, "name":"熊少文",...}
const handleSelectionChange = (val) => {
  //js数组的map，类似于Java的Stream流式处理中的map，作用：用于转换每个数据项
  selectedIds.value = val.map(emp => emp.id);
  console.log(selectedIds.value);
}
//当点击“编辑”按钮的处理逻辑
const handleEdit = async (index, row) => {
  //1. 先向后端发请求查询员工 todo
  const result = await getEmpById(row.id);
  if (result.code == 1) {
    //2. 将查询到的员工设置给dialog内的表单 todo
    empForm.value = result.data;
    //   将此员工信息的每个工作经历中  begin和end 赋值给此工作经历的exprrange数组
    const exprList = empForm.value.exprList;
    exprList.forEach(expr => {
      expr.exprrange = [expr.begin, expr.end];
    });
    //3. 将dialog的标题设置为“修改员工”
    dialogTitle.value = "修改员工";
    //4. 将dialog窗口显示出来
    dialogFormVisible.value = true;
  }
}
//批量删除
function batchDelete() {
  if (selectedIds.value.length == 0) {
    ElMessage.warning("请选择要删除的记录");
    return;
  }
  ElMessageBox.confirm('确定要删除吗?','提示',{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(async () => {
      //发请求，批量删除
      const result = await deleteEmpById(selectedIds.value);
      if (result.code == 1) {
        ElMessage.success('删除成功');
        search();
      } else {
        ElMessage.error('删除失败');
      }
    })
}
//当点击“删除”按钮的处理逻辑
const handleDelete = (index, row) => {
  //先弹出确认窗口，给用户一个警告确认
  ElMessageBox.confirm('此操作将永久删除该员工, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    //用户点击确定，发请求，删除数据
    const result = await deleteEmpById(row.id);
    if (result.code == 1) {
      ElMessage.success('删除成功');
      search();
    } else {
      ElMessage.error('删除失败');
    }
  })
}
//上传文件成功之后的处理。response是响应的结果
const handleAvatarSuccess = (response, uploadFile) => {
  empForm.value.image = response.data;
}
//上传之前的校验逻辑
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/png') {
    ElMessage.error('不支持的图片格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过 2MB!')
    return false
  }
  return true
}
</script>

<template>
  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchForm.gender" placeholder="请选择" clearable>
        <el-option v-for="g in genders" :label="g.name" :value="g.value" :key="g.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职日期">
      <el-date-picker v-model="searchForm.daterange" value-format="YYYY-MM-DD" type="daterange" range-separator="到"
        start-placeholder="开始日期" end-placeholder="结束日期" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="research">清空</el-button>
    </el-form-item>
  </el-form>

  <el-button type="primary " @click="showAddWin">
    新增员工
  </el-button>
  <el-button type="primary " @click="batchDelete">
    批量删除
  </el-button>
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="800">
    <el-form :model="empForm" label-width="80px">
      <!-- 第一行：用户名和姓名  -->
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="用户名">
            <el-input v-model="empForm.username" placeholder="请输入用户名，长度2~20个字"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名">
            <el-input v-model="empForm.name" placeholder="请输入姓名，长度2~10个字"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第2行：性别和手机号 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别">
            <el-select v-model="empForm.gender" placeholder="请选择性别" style="width:100%">
              <el-option v-for="g in genders" :label="g.name" :value="g.value" :key="g.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input v-model="empForm.phone" placeholder="请输入员工手机号" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第3行：职位与薪资 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="empForm.job" placeholder="请选择职位" style="width:100%">
              <el-option v-for="j in jobs" :label="j.name" :value="j.value" :key="j.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="empForm.salary" placeholder="请输入员工薪资" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第4行：所属部门与入职日期 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="empForm.deptId" placeholder="请选择部门" style="width:100%">
              <el-option v-for="d in depts" :label="d.name" :value="d.id" :key="d.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="empForm.entryDate" type="date" value-format="YYYY-MM-DD" placeholder="选择入职日期"
              style="width:100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第5行：头像 -->
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="头像">
            <!-- 
            文件上传：并不是使用axios上传的，而是使用了普通表单的形式
              action：文件上传的路径，表单数据提交的路径。需要我们自己手动添加/api前缀
              on-success：当文件上传成功之后的处理函数
              before-upload：文件上传之前的校验，通常用于限制上传的文件格式、大小等等
            -->
            <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
              :headers="{'token':userToken}"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="empForm.image" :src="empForm.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第6行：添加工作经历按钮 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作经历">
            <el-button type="success" @click="addExpr">添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第7行：工作经历 -->
      <el-row :gutter="20" v-for="(expr, index) in empForm.exprList" :key="index">
        <el-col :span="9">
          <el-form-item label="时间" label-width="70px">
            <el-date-picker v-model="expr.exprrange" value-format="YYYY-MM-DD" type="daterange" range-separator="到"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公司" label-width="50px">
            <el-input v-model="expr.company" placeholder="请输入公司名称" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位" label-width="50px">
            <el-input v-model="expr.job" placeholder="请输入职位" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button type="danger" @click="removeExpr(index)">删除</el-button>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
    @selection-change="handleSelectionChange">
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column label="姓名" prop="name" width="120"></el-table-column>
    <el-table-column label="性别" prop="gender">
      <template #default="scope">{{ scope.row.gender == 1 ? "男" : "女" }}</template>
    </el-table-column>
    <el-table-column label="头像" prop="image">
      <template #default="scope">
        <img :src="scope.row.image" style="height:50px;">
      </template>
    </el-table-column>
    <el-table-column label="所属部门" prop="deptName"></el-table-column>
    <el-table-column label="职位" prop="job">
      <template #default="scope">
        <!-- 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师 -->
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else>咨询师</span>
      </template>
    </el-table-column>
    <el-table-column label="入职日期" prop="entryDate"></el-table-column>
    <el-table-column label="最后操作时间" prop="updateTime" width="200"></el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />
</template>

<style scoped>
.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>